package com.rui.study.algorithm.T_调度任务的取消;


import java.util.concurrent.*;

import static com.rui.study.algorithm.PrintUtil.print;

/**
 * @program: study_20180903
 * @description:
 * @author: Yaowr
 * @create: 2018-10-25 17:15
 **/
public class Test {

    static ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(4, new SimpleThreadFactory(), new ThreadPoolExecutor.AbortPolicy());

    static ConcurrentHashMap<String, ScheduledFuture> futureList = new ConcurrentHashMap();

    public static void main(String[] args) {
        print("start...");

        for (int i = 0; i < 10; i++) {
            final int num = i;
            ScheduledFuture future = executor.schedule(()-> {
                print("任务" + num + "执行");
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
             }, i + 1, TimeUnit.SECONDS);
            futureList.put(String.valueOf(i) , future);
        }

        int count = 0;
        while (count++ < 10) {
            if (count % 3 == 0) {
                ScheduledFuture future = futureList.get(String.valueOf(count));
                if (future != null) {
                    print(count + " isDone: " + future.isDone());
                    print(count + " isCancelled: " + future.isCancelled());
                    print(count + " cancel: " + future.cancel(true));
                }
            }
//            print("ActiveCount: " + executor.getActiveCount());
//            print("TaskCount: " + executor.getTaskCount());
        }
        count = 0;
        while (count++ < 10) {
            ScheduledFuture future = futureList.get(String.valueOf(count));
            if (future != null) {
                print(count + " isDone: " + future.isDone());
                print(count + " isCancelled: " + future.isCancelled());
                print(count + " cancel: " + future.cancel(true));
            }
        }

        print("end");
    }

}
